package com.ruoyi.quality.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quality.domain.QualitySeamRate;
import com.ruoyi.quality.domain.bo.QualitySeamRateBo;
import com.ruoyi.quality.domain.vo.QualitySeamRateVo;
import com.ruoyi.quality.domain.vo.RecentHalfYearSeamVo;
import com.ruoyi.quality.mapper.QualitySeamRateMapper;
import com.ruoyi.quality.service.IQualitySeamRateService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.*;

import static com.ruoyi.common.Utils.getRecentHalfYearTimeRanges;

/**
 * 焊缝探伤信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-26
 */
@RequiredArgsConstructor
@Service
public class QualitySeamRateServiceImpl implements IQualitySeamRateService {

    private final QualitySeamRateMapper baseMapper;

    /**
     * 查询焊缝探伤信息
     */
    @Override
    public QualitySeamRateVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询焊缝探伤信息
     */
    @Override
    public List<QualitySeamRateVo> queryByIds(Collection<Long> ids){
        return baseMapper.selectVoBatchIds(ids);
    }

    /**
     * 查询焊缝探伤信息列表
     */
    @Override
    public TableDataInfo<QualitySeamRateVo> queryPageList(QualitySeamRateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<QualitySeamRate> lqw = buildQueryWrapper(bo);
        Page<QualitySeamRateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询焊缝探伤信息列表
     */
    @Override
    public List<QualitySeamRateVo> queryList(QualitySeamRateBo bo) {
        LambdaQueryWrapper<QualitySeamRate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<QualitySeamRate> buildQueryWrapper(QualitySeamRateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<QualitySeamRate> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getPartId() != null, QualitySeamRate::getPartId, bo.getPartId());
        lqw.eq(StringUtils.isNotBlank(bo.getDeptAbbreviation()), QualitySeamRate::getDeptAbbreviation, bo.getDeptAbbreviation());
        lqw.eq(bo.getInspector() != null, QualitySeamRate::getInspector, bo.getInspector());
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), QualitySeamRate::getUserName, bo.getUserName());
        lqw.eq(bo.getTotalLenth() != null, QualitySeamRate::getTotalLenth, bo.getTotalLenth());
        lqw.eq(bo.getDefectLenth() != null, QualitySeamRate::getDefectLenth, bo.getDefectLenth());
        lqw.eq(bo.getRate() != null, QualitySeamRate::getRate, bo.getRate());
        lqw.between(params.get("beginDate") != null && params.get("endDate") != null,
            QualitySeamRate::getDate ,params.get("beginDate"), params.get("endDate"));
        return lqw;
    }

    /**
     * 新增焊缝探伤信息
     */
    @Override
    public Boolean insertByBo(QualitySeamRateBo bo) {
        QualitySeamRate add = BeanUtil.toBean(bo, QualitySeamRate.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改焊缝探伤信息
     */
    @Override
    public Boolean updateByBo(QualitySeamRateBo bo) {
        QualitySeamRate update = BeanUtil.toBean(bo, QualitySeamRate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(QualitySeamRate entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除焊缝探伤信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 查询半年焊缝列表
     */
    @Override
    public List<RecentHalfYearSeamVo> getRecentHalfYearSeam(QualitySeamRateBo bo) {
        LocalDate currentDate = LocalDate.now();
        List<Map<String, Object>> timeRanges = getRecentHalfYearTimeRanges(currentDate);
        List<RecentHalfYearSeamVo> result = new ArrayList<>();

        timeRanges.forEach(item -> {
            bo.setParams(item);
            LambdaQueryWrapper<QualitySeamRate> lqw = buildQueryWrapper(bo);
            List<QualitySeamRateVo> seamRateVos = baseMapper.selectVoList(lqw);

            RecentHalfYearSeamVo vo = new RecentHalfYearSeamVo();
            if (!seamRateVos.isEmpty()) {
                double average = seamRateVos.stream()
                        .mapToDouble(QualitySeamRateVo::getRate)
                        .average()
                        .orElse(0.0);
                double multipliedAverage = average * 100;
                // 使用DecimalFormat格式化平均值保留四位小数
                DecimalFormat decimalFormat = new DecimalFormat("#.##");
                String formattedAverage = decimalFormat.format(multipliedAverage);
                double roundedAverage = Double.parseDouble(formattedAverage);
                vo.setRate(roundedAverage);
            }else {
                vo.setRate(0.00);
            }
            vo.setDate(String.valueOf(item.get("date")));
            result.add(vo);
        });

        return result;
    }

    /**
     * 计算指定条件下的焊缝总长、缺陷总长和相应合格率。
     *
     * @param bo 查询条件对象，包含指定人员、开始日期和结束日期
     * @return 包含焊缝总长、缺陷总长和相应合格率的Map，键为 "totalLength"、"defectLength" 和 "passRate"
     */
    @Override
    public Map<String, Object> calculateSeamRate(QualitySeamRateBo bo) {
        // 1. 查询指定人员在指定日期范围内的焊缝探伤信息
        List<QualitySeamRateVo> seamRateList = queryList(bo);

        // 2. 初始化返回的Map
        Map<String, Object> resultMap = new HashMap<>();

        // 3. 计算焊缝总长、缺陷总长和合格率
        double totalLength = 0.0;
        double defectLength = 0.0;
        for (QualitySeamRateVo seamRate : seamRateList) {
            totalLength += seamRate.getTotalLenth();
            defectLength += seamRate.getDefectLenth();
        }
        double passRate = (totalLength - defectLength) / totalLength * 100;
        passRate = Math.round(passRate * 100.0) / 100.0;

        // 4. 将焊缝总长、缺陷总长和合格率放入Map中
        resultMap.put("totalLength", totalLength);   // 焊缝总长
        resultMap.put("defectLength", defectLength); // 缺陷总长
        resultMap.put("passRate", passRate);         // 合格率

        // 5. 返回结果
        return resultMap;
    }
}
